package controllers

import (
	"GOPAAS/configs/config"
	"GOPAAS/internal/app/services"
	"fmt"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"strconv"
	"strings"
)

func Login(c *gin.Context) {
	redirect_url := c.DefaultQuery("redirect_url", "")
	if redirect_url == "" {
		redirect_url = c.Request.Referer()
	}
	_, err := c.Cookie(config.Conf.SessionKey)
	if err != nil {
		c.SetCookie(config.Conf.SessionKey, "login", 3600, "/", c.Request.Host, false, true)
	}
	c.HTML(http.StatusOK, "login.html", gin.H{
		"title":   "登录",
		"referer": redirect_url,
	})
}
func Index(c *gin.Context) {
	html_data := initial(c)
	html_data["title"] = "首页"
	c.HTML(http.StatusOK, "user.index.html", html_data)
}

// UserList 用户列表
func UserList(c *gin.Context) {
	html_data := initial(c)
	html_data["title"] = "用户列表"
	c.HTML(http.StatusOK, "user.list.html", html_data)
}

// UserEdit 用户创建/编辑
func UserEdit(c *gin.Context) {
	html_data := initial(c)
	user_id_str := c.Param("user_id")
	user_id, _ := strconv.Atoi(user_id_str)
	html_data["title"] = "新建用户"
	lang, _ := services.GetLang() //语言下拉列表
	html_data["lang"] = lang
	timeZone := services.GetTimeZone() //时区列表
	html_data["time_zone"] = timeZone
	html_data["user_id"] = user_id_str
	if user_id > 0 {
		UserService := services.GetUserService(int64(user_id))
		user_info, _ := UserService.GetUserInfo()
		html_data["data"] = user_info
		groups := services.GetAllGroups()
		html_data["groups"] = groups
		html_data["title"] = "编辑用户"
	} else {
		html_data["data"] = services.SignRes{}
	}
	c.HTML(http.StatusOK, "user.edit.html", html_data)
}

func Register(c *gin.Context) {
	c.HTML(http.StatusOK, "register", gin.H{
		"title": "注册",
	})
}
func ForgetPass(c *gin.Context) {
	c.HTML(http.StatusOK, "forget-pass", gin.H{
		"title": "忘记密码",
	})
}

// Image 头像图片路由（不限制访问）
func Image(c *gin.Context) {
	model := c.Query("model")
	res_id_str := c.Query("id")
	field := c.Query("field")
	res_id, _ := strconv.Atoi(res_id_str)
	size := c.Param("size")
	if field == "" {
		field = "image_" + size
	}
	attach_service := services.GetAttachService(0)
	//model = utils.GetTableNameByModel(model)
	attach, err := attach_service.GetAttach(model, int64(res_id), field)
	if err != nil {
		//utils.Error(c, -1, fmt.Sprintf("未找到图片：%s", err), nil)
		c.FileAttachment("./assets/img/no_picture.png", "avatar.jpg")
		return
	}
	fileExt := strings.Split(attach.Mimetype, "/")[1]
	//要下载的文件名称
	fileName := attach.Checksum + "." + fileExt
	filePath := config.Conf.DataDir + "/filestore/" + config.Conf.Database["postgresql"].DbName + "/" + attach.StoreFname
	fmt.Println("filePath:" + filePath)
	if _, path_err := os.Stat(filePath); os.IsNotExist(path_err) {
		c.FileAttachment("./assets/img/no_picture.png", "avatar.jpg")
		return
	}
	c.FileAttachment(filePath, fileName)
}

var HtmlData = gin.H{
	"user": services.SignRes{},
}

func initial(c *gin.Context) gin.H {
	fmt.Println(c.FullPath())
	session := sessions.Default(c)
	user_id := session.Get("user_id").(int64)
	UserService := services.GetUserService(user_id)
	_user, _ := UserService.GetUserInfo()
	HtmlData["user"] = _user
	route_path := c.FullPath()
	HtmlData["route_path"] = route_path
	module_index := strings.Index(route_path, "-")
	if module_index == -1 {
		module_index = len(route_path)
	}
	HtmlData["module"] = route_path[0:module_index]
	HtmlData["host"] = c.Request.Host

	return HtmlData
}
func Mqtt(c *gin.Context) {
	c.HTML(http.StatusOK, "mqtt.html", gin.H{})
}
